<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th>
            <input type="checkbox" v-model="checkAll" /> <span>全选</span>
          </th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(obj, index) in goodList" :key="index">
          <td><input type="checkbox" v-model="obj.checked" /></td>
          <td>{{ obj.name }}</td>
          <td>{{ obj.price }}</td>
          <td>
            <button @click="reduce(index)" :disabled="obj.num === 1">-</button>
            {{ obj.num }}
            <button @click="add(index)">+</button>
          </td>
          <td>{{ obj.price * obj.num }}</td>
          <td><button @click="del(index)">删除</button></td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td>合计:{{ totalPrice }}</td>
          <td colspan="5"></td>
        </tr>
      </tfoot>
    </table>
    <input type="text" placeholder="请输入商品名称" v-model="name" />
    <input type="text" placeholder="请输入商品价格" v-model="price" />
    <input type="text" placeholder="请输入商品数量" v-model="num" />
    <button @click="addGoods">添加</button>
  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  data() {
    return {
      name: "",
      price: "",
      num: "",
    };
  },
  computed: {
    ...mapState(["goodList"]),
    totalPrice() {
      let total = 0;
      this.goodList.forEach((item) => {
        if (item.checked === true) {
          return (total += item.num * item.price);
        }
      });
      return total;
    },
    checkAll: {
      set(val) {
        this.$store.commit("checked", val);
      },
      get() {
        return this.goodList.every((item) => item.checked === true);
      },
    },
  },
  methods: {
    reduce(index) {
      this.$store.commit("reduceNum", index);
    },
    add(index) {
      this.$store.commit("addNum", index);
    },
    del(index) {
      this.$store.commit("delete", index);
    },
    addGoods() {
      this.goodList.push({
        name: this.name,
        price: this.price,
        num: this.num,
        checked: false,
      });
      this.name = "";
      this.price = "";
      this.num = "";
    },
  },
};
</script>

<style>
</style>